package com.xm.data.service.impl;

import com.google.common.collect.Lists;
import com.xm.data.config.TableInitializer;
import com.xm.data.entiry.HistoryData;
import com.xm.data.entiry.StatType;
import com.xm.data.handler.DynamicTableHandler;
import com.xm.data.mapper.HistoryMapper;
import com.xm.data.service.HistoryDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class HistoryDataServiceImpl implements HistoryDataService {

    private final HistoryMapper historyMapper;
    private final TableInitializer tableInitializer;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void bulkSave(List<HistoryData> dataList, StatType type, int granularity) {
        String tableName = generateTableName(type, granularity);

        try {
            // 1. 确保表存在
            tableInitializer.createTableIfNotExists(type, granularity);

            // 2. 设置动态表名上下文
            DynamicTableHandler.setTableMeta(type, granularity);

            // 3. 分批次插入（每批500条）
            Lists.partition(dataList, 500).forEach(batch -> {
                historyMapper.batchInsert(tableName, batch);
            });
        } finally {
            DynamicTableHandler.clear();
        }
    }

    private String generateTableName(StatType type, int granularity) {
        return String.format("history_%s_%dm",
                type.name().toLowerCase(),
                granularity);
    }
}
